package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService{
    @Autowired
    private EmpMapper empMapper;


    /**
     * 条件分页查询班级信息
     *
     * @param name
     * @param begin
     * @param end
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult findPage(String name, LocalDate begin, LocalDate end, int page, int pageSize) {
        //1.设置分页参数
        IPage<Clazz> pageInfo = new Page<>(page,pageSize);
        //2.设置条件构造器
        LambdaQueryWrapper<Clazz> queryWrapper = Wrappers.<Clazz>lambdaQuery()
                .like(name != null,Clazz::getName,name)
                .between(begin != null && end != null,Clazz::getEndDate,begin,end)
                .orderByDesc(Clazz::getUpdateTime);
        IPage<Clazz> result = this.page(pageInfo,queryWrapper);
        List<Clazz> clazzList = result.getRecords();
        List<Long> empIdList = clazzList.stream().map(clazz -> clazz.getMasterId()).toList();
        empIdList = empIdList.stream().distinct().toList();
        List<Emp> empList = empMapper.selectByIds(empIdList);
        clazzList.forEach(clazz -> {
            empList.stream().filter(emp -> emp.getId().equals(clazz.getMasterId()))
                    .findFirst()
                    .ifPresent(emp -> clazz.setMasterName(emp.getName()));
            //设置班级状态，当开课时间在现在之后，状态为未开课，当结课时间在现在之前，是已结课，否则是已开课
            clazz.setStatus(clazz.getBeginDate().isAfter(LocalDate.now()) ? "未开课" : clazz.getEndDate().isBefore(LocalDate.now()) ? "已结课" : "已开课");
        });

        return new PageResult(result.getTotal(), clazzList);
    }
}
